package ui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

public class EmployeeManagerUI extends JFrame {
    private JTextField searchField;
    private JButton searchButton, addButton;
    private JTable employeeTable;
    private DefaultTableModel tableModel;
    private ArrayList<Employee> employees;


    public EmployeeManagerUI(){

    }

    public EmployeeManagerUI(String username) {

        initializeComponents(username);
        setupLayout();
        setupEventHandlers();
        setupWindowProperties();
        loadSampleData();
    }

    private void initializeComponents(String username) {
        // 设置标题
        setTitle("欢迎，"+username+"进入员工信息管理系统");

        // 初始化组件
        searchField = new JTextField(20);
        searchButton = new JButton("搜索");
        addButton = new JButton("添加");

        // 创建表格模型
        String[] columnNames = {"ID", "姓名", "部门", "职位", "工资"};
        tableModel = new DefaultTableModel(columnNames, 0);
        employeeTable = new JTable(tableModel);

        // 设置表格属性
        employeeTable.setRowHeight(25);
        employeeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 设置组件字体
        searchField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        searchButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        addButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));

        // 初始化员工列表
        employees = new ArrayList<>();
    }

    private void setupLayout() {
        // 设置主面板布局
        setLayout(new BorderLayout());

        // 创建顶部面板（输入框和按钮）
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        topPanel.add(new JLabel("搜索:"));
        topPanel.add(searchField);
        topPanel.add(searchButton);
        topPanel.add(addButton);
        add(topPanel, BorderLayout.NORTH);

        // 创建中心面板（表格）
        JScrollPane scrollPane = new JScrollPane(employeeTable);
        add(scrollPane, BorderLayout.CENTER);

        // 设置边框
        topPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "员工信息查询"));
        scrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "员工信息列表"));
    }

    private void setupEventHandlers() {
        // 搜索按钮事件处理
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performSearch();
            }
        });

        // 添加按钮事件处理
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddDialog();
            }
        });

        // 表格右键菜单事件处理
        employeeTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showContextMenu(e);
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showContextMenu(e);
                }
            }
        });

        // 输入框回车事件处理
        searchField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                performSearch();
            }
        });
    }

    private void performSearch() { // 定义一个名为performSearch的私有方法，用于执行搜索操作
        String keyword = searchField.getText().trim(); // 获取搜索字段中的文本，并去除首尾空白字符，存储在keyword变量中
        tableModel.setRowCount(0); // 清空表格模型中的所有行，准备显示新的搜索结果

        for (Employee emp : employees) { // 遍历employees集合中的每一个Employee对象
            if (emp.getName().contains(keyword) || // 检查员工姓名是否包含搜索关键词
                    emp.getDepartment().contains(keyword) || // 检查员工所属部门是否包含搜索关键词
                    emp.getPosition().contains(keyword)) { // 检查员工职位是否包含搜索关键词
                tableModel.addRow(new Object[]{ // 如果上述任意条件为真，则向表格模型中添加新的一行
                        emp.getId(), // 添加员工ID
                        emp.getName(), // 添加员工姓名
                        emp.getDepartment(), // 添加员工所属部门
                        emp.getPosition(), // 添加员工职位
                        emp.getSalary() // 添加员工工资
                });
            }
        }

        if (tableModel.getRowCount() == 0) { // 如果表格模型中没有添加任何行，即未找到匹配的员工信息
            JOptionPane.showMessageDialog(this, "未找到匹配的员工信息！", "提示", JOptionPane.INFORMATION_MESSAGE); // 弹出一个信息对话框，提示用户未找到匹配信息
        } // 结束if语句
    } // 结束performSearch方法

    private void showAddDialog() { // 定义一个名为showAddDialog的私有方法，用于显示添加员工的对话框
        // 创建对话框
        JDialog dialog = new JDialog(this, "添加员工", true); // 创建一个模式对话框，标题为“添加员工”
        dialog.setSize(400, 300); // 设置对话框的大小为400像素宽，300像素高
        dialog.setLocationRelativeTo(this); // 设置对话框相对于当前窗口居中显示

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridLayout(5, 2, 10, 10)); // 创建一个使用网格布局的面板，5行2列，单元格间距为10像素
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 设置面板的边框为空边框，边距为20像素

        // 添加表单字段
        formPanel.add(new JLabel("姓名:")); // 添加一个标签，显示“姓名:”
        JTextField nameField = new JTextField(); // 创建一个文本输入框，用于输入员工姓名
        formPanel.add(nameField); // 将姓名输入框添加到表单面板中

        formPanel.add(new JLabel("部门:")); // 添加一个标签，显示“部门:”
        JTextField departmentField = new JTextField(); // 创建一个文本输入框，用于输入员工部门
        formPanel.add(departmentField); // 将部门输入框添加到表单面板中

        formPanel.add(new JLabel("职位:")); // 添加一个标签，显示“职位:”
        JTextField positionField = new JTextField(); // 创建一个文本输入框，用于输入员工职位
        formPanel.add(positionField); // 将职位输入框添加到表单面板中

        formPanel.add(new JLabel("工资:")); // 添加一个标签，显示“工资:”
        JTextField salaryField = new JTextField(); // 创建一个文本输入框，用于输入员工工资
        formPanel.add(salaryField); // 将工资输入框添加到表单面板中

        // 添加按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10)); // 创建一个使用流式布局的面板，组件右对齐，间距为10像素
        JButton saveButton = new JButton("保存"); // 创建一个按钮，显示“保存”
        JButton cancelButton = new JButton("取消"); // 创建一个按钮，显示“取消”
        buttonPanel.add(saveButton); // 将保存按钮添加到按钮面板中
        buttonPanel.add(cancelButton); // 将取消按钮添加到按钮面板中

        // 添加到对话框
        dialog.add(formPanel, BorderLayout.CENTER); // 将表单面板添加到对话框的中间区域
        dialog.add(buttonPanel, BorderLayout.SOUTH); // 将按钮面板添加到对话框的底部区域


        // 事件处理
        saveButton.addActionListener(new ActionListener() { // 为保存按钮添加事件监听器
            @Override
            public void actionPerformed(ActionEvent e) { // 定义按钮点击事件的处理方法
                String name = nameField.getText().trim(); // 获取姓名输入框中的文本，并去除首尾空白字符
                String department = departmentField.getText().trim(); // 获取部门输入框中的文本，并去除首尾空白字符
                String position = positionField.getText().trim(); // 获取职位输入框中的文本，并去除首尾空白字符
                String salaryStr = salaryField.getText().trim(); // 获取工资输入框中的文本，并去除首尾空白字符

                if (name.isEmpty() || department.isEmpty() || position.isEmpty() || salaryStr.isEmpty()) { // 检查所有字段是否为空
                    JOptionPane.showMessageDialog(dialog, "所有字段都不能为空！", "错误", JOptionPane.ERROR_MESSAGE); // 如果有空字段，弹出错误对话框
                    return; // 结束方法
                }

                try {
                    double salary = Double.parseDouble(salaryStr); // 将工资字符串转换为double类型
                    Employee newEmployee = new Employee( // 创建一个新的Employee对象
                            employees.size() + 1, // 设置员工ID为当前员工列表大小加1
                            name, // 设置员工姓名
                            department, // 设置员工部门
                            position, // 设置员工职位
                            salary // 设置员工工资
                    );

                    employees.add(newEmployee); // 将新员工添加到员工列表中
                    updateTable(); // 更新表格显示
                    dialog.dispose(); // 关闭对话框
                    JOptionPane.showMessageDialog(EmployeeManagerUI.this, "员工添加成功！", "成功", JOptionPane.INFORMATION_MESSAGE); // 弹出成功对话框
                } catch (NumberFormatException ex) { // 捕获数字格式异常
                    JOptionPane.showMessageDialog(dialog, "工资必须是数字！", "错误", JOptionPane.ERROR_MESSAGE); // 弹出错误对话框，提示工资必须是数字
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() { // 为取消按钮添加事件监听器
            @Override
            public void actionPerformed(ActionEvent e) { // 定义按钮点击事件的处理方法
                dialog.dispose(); // 关闭对话框
            }
        });

        dialog.setVisible(true); // 设置对话框可见
    }

    private void showContextMenu(MouseEvent e) {
        int row = employeeTable.rowAtPoint(e.getPoint());
        if (row >= 0) {
            // 创建右键菜单
            JPopupMenu popupMenu = new JPopupMenu();

            JMenuItem editItem = new JMenuItem("修改");
            JMenuItem deleteItem = new JMenuItem("删除");

            popupMenu.add(editItem);
            popupMenu.add(deleteItem);

            // 修改菜单项事件
            editItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    editEmployee(row);
                }
            });

            // 删除菜单项事件
            deleteItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    deleteEmployee(row);
                }
            });

            popupMenu.show(employeeTable, e.getX(), e.getY());
        }
    }

    private void editEmployee(int rowIndex) {
        // 获取选中行的数据
        int id = (Integer) tableModel.getValueAt(rowIndex, 0);
        String name = (String) tableModel.getValueAt(rowIndex, 1);
        String department = (String) tableModel.getValueAt(rowIndex, 2);
        String position = (String) tableModel.getValueAt(rowIndex, 3);
        double salary = (Double) tableModel.getValueAt(rowIndex, 4);

        // 创建编辑对话框
        JDialog dialog = new JDialog(this, "编辑员工", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridLayout(5, 2, 10, 10));
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 添加表单字段
        formPanel.add(new JLabel("姓名:"));
        JTextField nameField = new JTextField(name);
        formPanel.add(nameField);

        formPanel.add(new JLabel("部门:"));
        JTextField departmentField = new JTextField(department);
        formPanel.add(departmentField);

        formPanel.add(new JLabel("职位:"));
        JTextField positionField = new JTextField(position);
        formPanel.add(positionField);

        formPanel.add(new JLabel("工资:"));
        JTextField salaryField = new JTextField(String.valueOf(salary));
        formPanel.add(salaryField);

        // 添加按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        // 添加到对话框
        dialog.add(formPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        // 事件处理
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String newName = nameField.getText().trim();
                String newDepartment = departmentField.getText().trim();
                String newPosition = positionField.getText().trim();
                String newSalaryStr = salaryField.getText().trim();

                if (newName.isEmpty() || newDepartment.isEmpty() || newPosition.isEmpty() || newSalaryStr.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "所有字段都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                try {
                    double newSalary = Double.parseDouble(newSalaryStr);

                    // 更新员工信息
                    for (Employee emp : employees) {
                        if (emp.getId() == id) {
                            emp.setName(newName);
                            emp.setDepartment(newDepartment);
                            emp.setPosition(newPosition);
                            emp.setSalary(newSalary);
                            break;
                        }
                    }

                    updateTable();
                    dialog.dispose();
                    JOptionPane.showMessageDialog(EmployeeManagerUI.this, "员工信息修改成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(dialog, "工资必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });

        dialog.setVisible(true);
    }

    private void deleteEmployee(int rowIndex) {
        int id = (Integer) tableModel.getValueAt(rowIndex, 0);
        int confirm = JOptionPane.showConfirmDialog(this,
                "确定要删除该员工吗？", "确认删除",
                JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

        if (confirm == JOptionPane.YES_OPTION) {
            // 从列表中移除员工
            employees.removeIf(emp -> emp.getId() == id);
            updateTable();
            JOptionPane.showMessageDialog(this, "员工删除成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void updateTable() {
        tableModel.setRowCount(0); // 清空表格

        for (Employee emp : employees) {
            tableModel.addRow(new Object[]{
                    emp.getId(),
                    emp.getName(),
                    emp.getDepartment(),
                    emp.getPosition(),
                    emp.getSalary()
            });
        }
    }

    private void loadSampleData() {
        // 添加一些示例数据
        employees.add(new Employee(1, "张三", "技术部", "开发工程师", 8000.0));
        employees.add(new Employee(2, "李四", "销售部", "销售经理", 12000.0));
        employees.add(new Employee(3, "王五", "人事部", "人事专员", 6000.0));
        employees.add(new Employee(4, "赵六", "财务部", "会计", 7500.0));
        employees.add(new Employee(5, "钱七", "技术部", "测试工程师", 7000.0));
        employees.add(new Employee(6, "孙八", "市场部", "市场专员", 6500.0));
        employees.add(new Employee(7, "周九", "技术部", "架构师", 15000.0));
        employees.add(new Employee(8, "吴十", "行政部", "行政助理", 5500.0));
        employees.add(new Employee(9, "郑十一", "技术部", "前端工程师", 8500.0));
        employees.add(new Employee(10, "王十二", "销售部", "销售代表", 6000.0));
        employees.add(new Employee(11, "陈十三", "人事部", "招聘专员", 6200.0));
        employees.add(new Employee(12, "刘十四", "财务部", "出纳", 5800.0));
        employees.add(new Employee(13, "杨十五", "技术部", "后端工程师", 8200.0));
        employees.add(new Employee(14, "黄十六", "市场部", "市场主管", 9000.0));
        employees.add(new Employee(15, "朱十七", "技术部", "运维工程师", 7800.0));
        employees.add(new Employee(16, "秦十八", "行政部", "行政主管", 8800.0));
        employees.add(new Employee(17, "何十九", "销售部", "销售主管", 10000.0));
        employees.add(new Employee(18, "高二十", "技术部", "项目经理", 13000.0));
        employees.add(new Employee(19, "林二十一", "人事部", "人力资源经理", 11000.0));
        employees.add(new Employee(20, "徐二十二", "财务部", "财务主管", 10500.0));

        // 初始加载数据到表格
        updateTable();
    }

    private void setupWindowProperties() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null); // 居中显示
        setResizable(false); // 不可调整大小
    }

    // 员工类
    private static class Employee {
        private int id;
        private String name;
        private String department;
        private String position;
        private double salary;

        public Employee(int id, String name, String department, String position, double salary) {
            this.id = id;
            this.name = name;
            this.department = department;
            this.position = position;
            this.salary = salary;
        }

        // Getter和Setter方法
        public int getId() { return id; }
        public void setId(int id) { this.id = id; }

        public String getName() { return name; }
        public void setName(String name) { this.name = name; }

        public String getDepartment() { return department; }
        public void setDepartment(String department) { this.department = department; }

        public String getPosition() { return position; }
        public void setPosition(String position) { this.position = position; }

        public double getSalary() { return salary; }
        public void setSalary(double salary) { this.salary = salary; }
    }

    // 主方法

}